<?php


namespace App\Http\Controllers\Admin\Access;


use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
//路由
class RouteController extends BaseController
{
    /**
     * @api {get} /access/route 路由列表
     *
     * @apiGroup 新权限模块
     *
     * @apiParam {string} is_bind_access 是否绑定权限
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，1-100之间，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1,
    "ctr_dir": "ThreeCheck", 控制器所在目录
    "ctr": "ThreeCheckController", 控制器名称
    "action": "adminStat", 方法名
    "uri": "three/check/stat", 路由地址
    "method": "get", 请求方式
    "is_bind_access": 0, 是否已经绑定权限，1：是；0：否；（是用绿色，否则不正常，建议用红色提示）
    "is_exist": 0 是否存在，1：是；0：否
    }
    ],
    "first_page_url": "http://qipaoadmin/access/route?page=1",
    "from": 1,
    "last_page": 86,
    "last_page_url": "http://qipaoadmin/access/route?page=86",
    "next_page_url": "http://qipaoadmin/access/route?page=2",
    "path": "http://qipaoadmin/access/route",
    "per_page": 10,
    "prev_page_url": null,
    "to": 10,
    "total": 856
    },
    "message": ""
    }
     */
    public function list(Request $request)
    {
        $param = $request->only('is_bind_access', 'page', 'page_size');
        $v = app('validator')->make($param,[
            'is_bind_access' => 'integer|in:-1,0,1',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $isBindAccess = $param['is_bind_access'] ?? -1;
        $pageSize = $param['page_size'] ?? 10;

        //查询已绑定权限的路由id
        $bindRouteIds = app('model_access_route_join')->getAllRouteIds();
        //查询数据库存在但路由文件中不存在的路由id
        $noExistRouteIds = app('repo_access')->getNoEntryOrNoExistRoute(2);

        $whereFunc = [];
        if ($isBindAccess == 1) {
            $whereFunc = function ($query) use ($bindRouteIds) {
                $query->whereIn('id', $bindRouteIds);
            };
        } else if ($isBindAccess == 0) {
            $whereFunc = function ($query) use ($bindRouteIds) {
                $query->whereNotIn('id', $bindRouteIds);
            };
        }

        $list = app('model_route')
            ->select('id', 'ctr_dir', 'ctr', 'action', 'uri', 'method')
            ->where($whereFunc)
            ->orderBy('id', 'desc')
            ->paginate($pageSize)->toArray();

        foreach ($list['data'] as &$v) {
            if (in_array($v['id'], $bindRouteIds)) {
                $v['is_bind_access'] = 1;
            } else {
                $v['is_bind_access'] = 0;
            }
            if (in_array($v['id'], $noExistRouteIds)) {
                $v['is_exist'] = 0;
            } else {
                $v['is_exist'] = 1;
            }
        }
        return Response::sendData($list);
    }

    /**
     * @api {get} /access/route/new 新路由列表
     *
     * @apiGroup 新权限模块
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "ctr_dir": "Access",
    "ctr": "RouteController",
    "action": "list",
    "uri": "access/route",
    "method": "get"
    }
    ],
    "message": ""
    }
     */
    public function newRouteList()
    {
        $noEntryRoutes = app('repo_access')->getNoEntryOrNoExistRoute();
        return Response::sendData($noEntryRoutes);
    }

    /**
     * @api {post} /access/route/new-entry 新路由录入到数据库
     *
     * @apiGroup 新权限模块
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [],
    "message": ""
    }
     */
    public function newRouteEntry()
    {
        $noEntryRoutes = app('repo_access')->getNoEntryOrNoExistRoute();
        $res = app('model_route')->insert($noEntryRoutes);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '录入失败，请重试');
    }

    /**
     * @api {delete} /access/route 删除路由
     *
     * @apiGroup 新权限模块
     *
     * @apiParam {string} ids 路由id，多个用英文逗号隔开，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function del(Request $request)
    {
        $param = $request->only('ids');
        $v = app('validator')->make($param,[
            'ids' => 'required',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $ids = explode(',', $param['ids']);

        $queryIds = app('model_route')->select('id')->whereIn('id', $ids)->pluck('id')->toArray();
        if (count($queryIds) != count($ids)) throw new BasicException(0, '路由id错误');

        //如果还有权限在使用的路由不能删除
        $accessIds = app('model_access_route_join')->select('access_id')->whereIn('route_id', $ids)->pluck('access_id')->toArray();
        if ($accessIds) {
            $accessNames = app('model_access')->select('name')->whereIn('id', $accessIds)->pluck('name')->toArray();
            throw new BasicException(0, '路由关联了权限，无法删除。关联的权限：' . implode('，', $accessNames));
        }

        //删除
        $res = app('model_route')->whereIn('id', $ids)->delete();
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '删除失败');
    }

    /**
     * @api {get} /access/route/ctr-route 获取控制器及对应的路由
     *
     * @apiGroup 新权限模块
     *
     * @apiParam {string} ctr_initials 控制器首字母，默认A
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
        {
        "ctr_dir": "ContentManager", 控制器目录
        "ctr": "AboutClassifyController" 控制器
        "children": [
                {
                "id": 350,
                "action": "create",
                "uri": "content-manager/about-classify",
                "method": "post"
                }
            ]
        }
    ],
    "message": ""
    }
     */
    public function getControllerWithRoute(Request $request)
    {
        $ctrInitials = $request->ctr_initials ?? 'A';

        $list = app('model_route')
            ->select('ctr_dir', 'ctr')
            ->where('ctr', 'like', "$ctrInitials%")
            ->groupBy('ctr')->groupBy('ctr_dir')
            ->get()->toArray();
        foreach ($list as &$v) {
            $v['children'] = app('model_route')
                ->select('id', 'action', 'uri', 'method')
                ->where('ctr_dir', $v['ctr_dir'])
                ->where('ctr', $v['ctr'])
                ->get()->toArray();
        }
        return Response::sendData($list);
    }
}